import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:azring/core/repository/default_api.dart';
import 'package:azring/core/controllers/auth_controller.dart';
import 'group_member_state.dart';

class GroupMemberLogic extends GetxController {
  final state = GroupMemberState();
  final _api = DefaultApi();
  final TextEditingController inviteController = TextEditingController();

  @override
  void onInit() {
    super.onInit();
    // 从路由参数获取群组信息
    final args = Get.arguments as Map<String, dynamic>?;
    if (args != null) {
      state.groupId.value = args['groupId'] ?? 0;
      state.groupName.value = args['groupName'] ?? '';
      state.groupCode.value = args['groupCode'] ?? '';
    }
    loadGroupMembers();
  }

  @override
  void onClose() {
    inviteController.dispose();
    super.onClose();
  }

  /// 加载群组成员列表
  Future<void> loadGroupMembers() async {
    try {
      state.isLoading.value = true;
      final response = await _api.queryGroupMemberListGet<Map<String, dynamic>>(
        id: state.groupId.value,
        isShowLoading: false,
      );

      if (response != null && response['code'] == 200) {
        final List<dynamic> data = response['data'] ?? [];
        state.memberList.value = data.map((item) {
          return {
            'id': item['id'],
            'groupId': item['groupId'],
            'userId': item['userId'],
            'memberAccount': item['memberAccount'],
            'memberName': item['memberName'] ?? '未知用户',
            'memberAvatar': item['memberAvatar'] ?? '',
            'joinTime': item['joinTime'] ?? '',
            'idSynchronize': item['idSynchronize'] ?? '0',
            'memberType': item['memberType'] ?? '2', // 1-创建者, 2-成员
            'remark': item['remark'],
          };
        }).toList();

        // 检查当前用户是否是群主
        final currentUserId = AuthController.to.user?.userId;
        if (currentUserId != null) {
          final currentUserMember = state.memberList.firstWhereOrNull(
            (member) => member['userId'] == currentUserId,
          );
          state.isCreator.value = currentUserMember?['memberType'] == '1';
        }
      }
    } catch (e) {
      print('加载群组成员失败: $e');
      Toast.show('加载成员列表失败');
    } finally {
      state.isLoading.value = false;
    }
  }

  /// 邀请成员
  Future<void> inviteMember() async {
    final applyInfo = inviteController.text.trim();
    
    if (applyInfo.isEmpty) {
      Toast.show('请输入手机号或邮箱');
      return;
    }

    // 验证手机号或邮箱格式
    final phoneRegex = RegExp(r'^1[3-9]\d{9}$');
    final emailRegex = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$');
    
    if (!phoneRegex.hasMatch(applyInfo) && !emailRegex.hasMatch(applyInfo)) {
      Toast.show('请输入正确的手机号或邮箱');
      return;
    }

    try {
      final response = await _api.applyJoinGroupPost<Map<String, dynamic>>(
        applyInfo: applyInfo,
        groupCode: state.groupCode.value,
        joinType: '1', // 1-邀请加入
        isShowLoading: true,
      );

      if (response != null && response['code'] == 200) {
        Toast.show('邀请已发送');
        inviteController.clear();
        // 刷新成员列表
        await loadGroupMembers();
      } else {
        Toast.show(response?['msg'] ?? '邀请失败');
      }
    } catch (e) {
      print('邀请成员失败: $e');
      Toast.show('邀请失败');
    }
  }

  /// 修改备注
  void editRemark(Map<String, dynamic> member) {
    final TextEditingController remarkController = TextEditingController(
      text: member['remark'] ?? '',
    );
    bool isDisposed = false;

    Get.dialog(
      AlertDialog(
        title: const Text('修改备注'),
        content: TextField(
          controller: remarkController,
          decoration: InputDecoration(
            hintText: '请输入备注名称',
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(8),
            ),
          ),
          maxLength: 20,
        ),
        actions: [
          TextButton(
            onPressed: () {
              Get.back();
              if (!isDisposed) {
                isDisposed = true;
                remarkController.dispose();
              }
            },
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () async {
              final newRemark = remarkController.text.trim();
              if (newRemark.isEmpty) {
                Toast.show('备注不能为空');
                return;
              }

              Get.back();
              
              try {
                final response = await _api.editGroupMemberRemarkPut<Map<String, dynamic>>(
                  id: member['id'],
                  memberName: newRemark,
                  isShowLoading: true,
                );

                if (response != null && response['code'] == 200) {
                  Toast.show('备注修改成功');
                  // 刷新成员列表
                  await loadGroupMembers();
                } else {
                  Toast.show(response?['msg'] ?? '修改备注失败');
                }
              } catch (e) {
                print('修改备注失败: $e');
                Toast.show('修改备注失败');
              } finally {
                if (!isDisposed) {
                  isDisposed = true;
                  remarkController.dispose();
                }
              }
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  /// 切换编辑模式
  void toggleEditMode() {
    state.isEditMode.value = !state.isEditMode.value;
  }

  /// 移除群组成员
  void removeMember(Map<String, dynamic> member) {
    final memberName = member['memberName'] ?? '该成员';
    Get.dialog(
      AlertDialog(
        title: const Text('确认移除'),
        content: Text('确定要将 $memberName 移出群组吗？'),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () async {
              Get.back();
              
              try {
                final response = await _api.removeGroupMemberDel<Map<String, dynamic>>(
                  id: member['id'].toString(),
                  isShowLoading: true,
                );

                if (response != null && response['code'] == 200) {
                  Toast.show('已移除成员');
                  // 刷新成员列表
                  await loadGroupMembers();
                } else {
                  Toast.show(response?['msg'] ?? '移除成员失败');
                }
              } catch (e) {
                print('移除成员失败: $e');
                Toast.show('移除成员失败');
              }
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.red,
            ),
            child: const Text(
              '移除',
              style: TextStyle(color: Colors.white),
            ),
          ),
        ],
      ),
    );
  }

  /// 退出群组
  void leaveGroup() {
    Get.dialog(
      AlertDialog(
        title: const Text('确认退出'),
        content: const Text('确定要退出该群组吗？'),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () async {
              Get.back();
              
              try {
                // 找到当前用户的成员ID
                final currentUserId = AuthController.to.user?.userId;
                final currentUserMember = state.memberList.firstWhereOrNull(
                  (member) => member['userId'] == currentUserId,
                );

                if (currentUserMember == null) {
                  Toast.show('未找到当前用户信息');
                  return;
                }

                final response = await _api.removeGroupMemberDel<Map<String, dynamic>>(
                  id: currentUserMember['id'].toString(),
                  isShowLoading: true,
                );

                if (response != null && response['code'] == 200) {
                  Toast.show('已退出群组');
                  // 返回上一页，并传递刷新标记
                  Get.back(result: true);
                } else {
                  Toast.show(response?['msg'] ?? '退出群组失败');
                }
              } catch (e) {
                print('退出群组失败: $e');
                Toast.show('退出群组失败');
              }
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.red,
            ),
            child: const Text(
              '退出',
              style: TextStyle(color: Colors.white),
            ),
          ),
        ],
      ),
    );
  }

  /// 解散群组
  void dismissGroup() {
    Get.dialog(
      AlertDialog(
        title: const Text('确认解散'),
        content: const Text('解散群组后，所有成员将被移除，此操作不可恢复。确定要解散群组吗？'),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () async {
              Get.back();
              
              try {
                final response = await _api.removeGroupDel<Map<String, dynamic>>(
                  id: state.groupId.value.toString(),
                  isShowLoading: true,
                );

                if (response != null && response['code'] == 200) {
                  Toast.show('群组已解散');
                  // 返回上一页，并传递刷新标记
                  Get.back(result: true);
                } else {
                  Toast.show(response?['msg'] ?? '解散群组失败');
                }
              } catch (e) {
                print('解散群组失败: $e');
                Toast.show('解散群组失败');
              }
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.red,
            ),
            child: const Text(
              '解散',
              style: TextStyle(color: Colors.white),
            ),
          ),
        ],
      ),
    );
  }

  /// 刷新数据
  @override
  Future<void> refresh() async {
    await loadGroupMembers();
  }
}
